package PerDNSServer2;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * @Author: 0162977
 * @Date: 2020/12/3 16:07
 */
public class ListenThread implements Runnable {

    DatagramSocket socket = null;
    DatagramPacket packet = null;

    public ListenThread(DatagramSocket socket,DatagramPacket packet) {
        this.socket = socket;
        this.packet = packet;
    }

    @Override
    public void run() {
        String info = null;
        DatagramPacket packet2 = null;
        info = new String(packet.getData(), 0, packet.getLength());
        System.out.println(info);
        try {
            String[] res = info.split(",");
            String website = null;
            String portNext = null;
            if (res.length == 2){
                website = res[0];
                portNext = res[1];
            }else {
                website = res[1];
                portNext = res[2];
            }

            //转发出去
            InetAddress address = null;
            address = InetAddress.getByName("localhost");
            String mappingIp = ShareSpaceAndFun.findMapping(website);
            byte[] data2 = ("0,"+website+","+mappingIp).getBytes();
            packet2 = new DatagramPacket(data2, data2.length, address, Integer.parseInt(portNext));
            socket.send(packet2);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}